package com.xingda.packing.dmds.service;

import com.xingda.packing.dmds.domain.ShuntProductionLine;
import com.xingda.packing.dmds.shunt.generate.TaskGenerateService;
import com.xingda.packing.dmds.shunt.handle.TaskHandleService;
import com.xingda.packing.dmds.shunt.listener.TaskListenerService;
import com.xingda.packing.dmds.task.ticket.AbstractTaskTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component("taskManagerDMDSService4")
public class TaskManagerService4 extends Thread {
    @Resource
    private ShuntProductionLine shuntProductionLine;
    @Resource
    private TaskGenerateService generateService;
    @Resource
    private TaskHandleService handleService;
    @Resource
    private TaskListenerService listenerService;

    @Override
    public void run() {
        while (true) {
            try {
                if (shuntProductionLine.initRunning(4)) {
                    AbstractTaskTicket taskTicket = generateService.generate(shuntProductionLine, 4);
                    if (Objects.nonNull(taskTicket)) {
                        if (shuntProductionLine.checkCanAssignTaskTicket(4)) {
                            shuntProductionLine.assignTaskTicket(taskTicket, 4);
                        }
                    }
                }
                if (handleService.accept(shuntProductionLine, 4)) {
                    handleService.process(shuntProductionLine, 4);
                }
                if (listenerService.accept(shuntProductionLine, 4)) {
                    listenerService.monitor(shuntProductionLine, 4);
                }
                TimeUnit.MILLISECONDS.sleep(1500);
            } catch (Exception e) {
                log.error("分流区启动错误", e);
                shuntProductionLine.setInitRunning(4,false);
                shuntProductionLine.setInitRunning(4,true);
                shuntProductionLine.start(4);
                break;
            }
        }
    }
}
